package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;


@Slf4j
@Service
@Transactional
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    //文件上传
    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    /**
     * 素材图片上传
     *
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {

        //1.检查参数
        if (multipartFile == null || multipartFile.getSize() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.上传图片到minio中
        String filePrefix = UUID.randomUUID().toString().replace("-", "");
        String originalFilename = multipartFile.getOriginalFilename();
        String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //文件名
        String filename = filePrefix + fileSuffix;
        String fileId = null;
        try {
            fileId = fileStorageService.uploadImgFile("", filename, multipartFile.getInputStream());
            log.info("上传图片到minio中,fileId:{}", fileId);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("WmMaterialServiceImpl-上传文件失败");
        }
        //3.保存图片到数据库中
        WmMaterial material = new WmMaterial();
        material.setUserId(WmThreadLocalUtil.getUser().getId());
        material.setUrl(fileId);
        material.setIsCollection((short) 0);
        material.setType((short) 0);
        material.setCreatedTime(new Date());
        //保存
        wmMaterialMapper.insert(material);
        //4.返回结果
        return ResponseResult.okResult(material);
    }

    /**
     * 素材列表查询
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmMaterialDto dto) {

        //1.检查参数
        dto.checkParam();
        // 2.分页查询
        IPage page = new Page(dto.getPage(), dto.getSize());
        //条件构造器
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 是否收藏
        if (dto.getIsCollection() != null && dto.getIsCollection() == 1) {
            lambdaQueryWrapper.eq(WmMaterial::getIsCollection, dto.getIsCollection());
        }
        // 按照用户查询( 根据用户的id查询素材信息
        lambdaQueryWrapper.eq(WmMaterial::getUserId, WmThreadLocalUtil.getUser().getId());
        // 按照时间倒序
        lambdaQueryWrapper.orderByDesc(WmMaterial::getCreatedTime);

        // 3.封装结果返回
        wmMaterialMapper.selectPage(page, lambdaQueryWrapper);
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        responseResult.setData(page.getRecords());

        return responseResult;
    }

    /**
     * 素材图片删除
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult delPicture(Integer id) {

        //1.检查参数
        if (id == null || id == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.当前素材id是否关联文章
        WmNewsMaterial wmNewsMaterial = wmNewsMaterialMapper.selectOne(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId,id));
        if (wmNewsMaterial != null) {
            return ResponseResult.errorResult(501, "当前素材已关联其他文章");
        }

        //3.查询数据
        WmMaterial material = wmMaterialMapper.selectById(id);
        if (material == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //4.删除minio中的图片
        try {
            fileStorageService.delete(material.getUrl());
        } catch (Exception e) {
            return ResponseResult.errorResult(501, "文件删除失败");
        }
        //5.删除数据库
        wmMaterialMapper.deleteById(id);
        //6.返回数据
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 收藏素材图片
     *
     * @param id
     * @return
     */
    public ResponseResult collectPicture(Integer id) {
        //1.检查参数
        if (id == null || id == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询数据
        WmMaterial material = wmMaterialMapper.selectById(id);
        if (material == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.修改数据
        material.setIsCollection((short) 1);
        wmMaterialMapper.updateById(material);
        //4.返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    /**
     * 取消收藏素材图片
     *
     * @param id
     * @return
     */
    public ResponseResult cancelCollectPicture(Integer id) {
        //1.检查参数
        if (id == null || id == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询数据
        WmMaterial material = wmMaterialMapper.selectById(id);
        if (material == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.修改数据
        material.setIsCollection((short) 0);
        wmMaterialMapper.updateById(material);
        //4.返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
